chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
	switch(request.type) {
    case 'transfer':
			if (request.status) {
				console.log('开启转账')
        localStorage.transfer_status = '1';
        if(window.location.pathname == "/payment/transfer/index.htm"){
          window.location.reload();
        }else {
          chrome.extension.sendMessage( { type: 'transfer_empty' } );
          localStorage.transfer_status = '0';
          window.location.href = "https://bizfundprod.alipay.com/payment/transfer/index.htm";
        }
			} else {
				localStorage.transfer_status = '0';
				console.log('停止转帐')
			}
			break;
    case 'forward':
			if (request.status) {
				console.log('开启提现')
				localStorage.forward_status = '1';
			} else {
				console.log('停止提现')
				localStorage.forward_status = '0';
			}
			break;
    case 'flush':
			if (request.status) {
				console.log('开启刷新')
				sessionStorage.flush_status = '1';
			} else {
				console.log('停止刷新')
				sessionStorage.flush_status = '0';
			}
      break;
    case 'info':
      // money: 最低转账金额
      // fee: 手续费率
      // payee_account: 收款账号
      // pay_pwd: 支付密码
      // interval: 轮询时长(秒)
      localStorage.transfer_info = JSON.stringify({
        money: request.data.money * 1,
        fee: request.data.fee * 1 || 0.002,
        payee_account: request.data.payee_account,
        pay_pwd: request.data.pay_pwd,
        interval: request.data.interval || 5
      });
      break;
    case 'clear':
      localStorage.removeItem('transfer_info');
      break;
	}
})

setInterval(function() {
  if(localStorage.transfer_status == '1'){
		checkTransfer();
	}
}, 3000)

function checkTransfer() {
  if(!localStorage.transfer_info){
    chrome.extension.sendMessage( { type: 'transfer_empty' } );
    localStorage.transfer_status = '0';
		alert('没有转账信息!');
		return true;
  }
  window.transfer_info = JSON.parse(localStorage.transfer_info);
  if (window.location.pathname == '/payment/transfer/index.htm') {
    if($('#J_paymentForm > div.summary.fn-clear > div > div').text() == '该账户余额支付功能关闭，不可将资金转出。'){
			alert('无法转账');
			return true;
    }
    if(!transfer(1) && localStorage.transfer_status == '1'){
			let interval = window.transfer_info.interval || 5;
			setTimeout(function(){
				window.location.reload();
			}, parseInt(Math.random() * 4) * 1000 + interval * 1000);
		}
  } else if (window.location.pathname == '/payment/transfer/check.htm') {
    let checkSafe = $('#J_transferCheckForm > div.mi-form-item.pay-password-item > div.ui-securitycore.ui-securitycore-tip.J-securitycoreTip > div > div.ui-form-explain').text();
    if(checkSafe == '安全设置检测成功！无需短信校验。'){
      if(!$('#payPassword_rsainput').is(':hidden')){
        $('#payPassword_rsainput').focus();
        setTimeout(function(){
          transfer(2);
        }, Math.random() * 2000 + 1000);
      }
    }else if(checkSafe == '支付宝正在检测你的安全设置...'){
      setTimeout(checkTransfer, 1000);
    }
  } else if(window.location.pathname == '/payment/transfer/detail.htm'){
		try{
			if($('#J_transferDetailPage > div.ui-resultstep-container.fn-clear.ui-resultstep-two > ul > li.ui-resultstep-item.ui-resultstep-last.ui-resultstep-finish.ui-resultstep-current > div.ui-resultstep-steptext').text().indexOf('成功') !== false){
				setTimeout(function(){
					window.location.href = "https://bizfundprod.alipay.com/payment/transfer/index.htm";
				}, Math.random() * 3000 + 3000);
			}else {
				alert('失败');
			}
		}catch{
			alert('失败');
		}
	}else if(window.location.pathname == '/error.htm'){
		try{
			window.location.href = "https://bizfundprod.alipay.com/payment/transfer/index.htm";
		}catch{
			alert('失败');
		}
	}
}

function transfer(step) {
  let transfer_info = window.transfer_info;
  switch(step) {
    case 1:
      let balance = $('#J_paymentForm > div.summary.fn-clear > div > span > em > span > span').text().replace(/,/g, '');
      if(transfer_info.money == undefined || balance <= transfer_info.money ){
				console.log('余额' + ' < ' + '设定的转账金额');
				return false;
      }
      let fee = transfer_info.fee * balance;
			if(fee < 2){
				fee = 2;
      }
      if(fee > 25) {
        fee = 25;
      }
      let money = Math.floor(balance - fee);
      setTimeout(function(){
        if ($('#J_payeeShowAccount').val()) {
          setTimeout(() => {
            if ($('#J_transferAmount').val()) {
              document.getElementById('J_paymentForm').submit();
            } else {
              $('#J_transferAmount').focus();
              setTimeout(() => {
                $('#J_transferAmount').val(2);
              }, Math.random() * 2000 + 1000)
            }
          }, Math.random() * 2000 + 1000)
        } else {
          $('#J_payeeShowAccount').focus();
          setTimeout(() => {
            $('#J_payeeShowAccount').val(transfer_info.payee_account);
          }, Math.random() * 2000 + 1000)
        }
      }, Math.random() * 500 + 1000);
      return true;
    case 2:
      $('#payPassword_rsainput').val(transfer_info.pay_pwd);
      setTimeout(function(){
        $('#smsSendChk').click();
      }, Math.random() * 1000 + 1500);
      return true;
  }
}
